package com.qd.panda.api;

import com.cdqidi.dto.ApiResult;
import com.cdqidi.dto.ApiResultWrapper;
import com.cdqidi.util.IpHelper;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.qd.panda.service.commodity.CommodityDcService;
import lombok.RequiredArgsConstructor;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;

/**
 * 对接来自数据中心同步的数据
 *
 * @author sjk
 */
@RequiredArgsConstructor
@Validated
@RestController
@RequestMapping("/api/v1/")
@Slf4j
public class ApiCommodityController {
    private final CommodityDcService commodityDcService;
    private final ObjectMapper objectMapper;
    private final HttpServletRequest request;
    private static final String WHITE = "10.18.100.50";

    /**
     * 接收同步过来的商品信息
     *
     * @param json json数据
     * @return 成功
     */
    @SneakyThrows
    @PostMapping(value = "/dc/syncCommodity")
    public ApiResultWrapper<ObjectNode> syncCommodity(@RequestBody String json) {
        String ip = IpHelper.getIpAddress(request);
        boolean pass = WHITE.equals(ip);
        log.info("数据中心同步数据,IP: {},是否白名单: {}", ip, pass);
        JsonNode jsonNode = objectMapper.readTree(json);
        int type = jsonNode.get("type").asInt();
        JsonNode data = jsonNode.get("data");
        if (type == 1) {
            log.info("收到数据中心的商品数据: {}", data);
            commodityDcService.syncData(data.toString());
        } else if (type == 2) {
            log.info("收到数据中心的卡密数据: {}", data);
            commodityDcService.syncCardInfo(data.toString());
        } else {
            return ApiResult.error("未知类型");
        }
        return ApiResult.success();
    }
}
